#ifndef A8_ICONV_H
#define A8_ICONV_H

#ifndef _WIN32
#include <iconv.h>
#endif

static int wstring2utf8(const std::wstring& ws, std::string& utf8str)
{
#ifdef _WIN32
	int textlen = WideCharToMultiByte(CP_UTF8, 
									  0, 
									  ws.c_str(), 
									  -1, 
									  NULL, 
									  0, 
									  NULL, 
									  NULL);
	if(textlen <= 0){
		return textlen;
	}
	char* buf = new char[textlen + 1];
	memset(buf, 0, textlen + 1);
	textlen = WideCharToMultiByte(CP_UTF8, 
								0, 
							   ws.c_str(), 
							   -1, 
							   buf, 
							   textlen + 1, 
								   NULL, 
							   NULL);
	if (textlen){
		utf8str = buf;
	}
	delete [] buf;
	return textlen;
#else
    return 0;
#endif
}

static int utf8_to_gbk(const std::string& utf8str, std::string& gbkstr)
{
#ifdef _WIN32
	int len = MultiByteToWideChar(CP_UTF8, 
								  0, 
								  utf8str.c_str(), 
								  -1, 
								  NULL, 
								  0);  
    unsigned short * wszGBK = new unsigned short[len + 1];  
    memset(wszGBK, 0, len * 2 + 2);  
    MultiByteToWideChar(CP_UTF8, 
						0, 
						(LPCTSTR)utf8str.c_str(), 
						-1, 
						wszGBK, 
						len);  
  
    len = WideCharToMultiByte(CP_ACP, 
							  0, 
							  wszGBK, 
							  -1, 
							  NULL, 
							  0, 
							  NULL, 
							  NULL);  
    char *szGBK = new char[len + 1];  
    memset(szGBK, 0, len + 1);  
    WideCharToMultiByte(CP_ACP,
						0, 
						wszGBK, 
						-1, 
						szGBK, 
						len, 
						NULL, 
						NULL);  
    //strUTF8 = szGBK;  
	gbkstr.assign(szGBK, strlen(szGBK));
    delete[]szGBK;  
    delete[]wszGBK;  
	return 1;
#else
	iconv_t conv = iconv_open("gbk", "utf-8");
	if(conv == (iconv_t)-1){
		return -1;
	}
	char *inbuf = (char*)utf8str.c_str();
	size_t inlen = utf8str.size();
	char *outbuf = (char*)malloc(inlen * 4);
	size_t outlen = inlen * 4;
	memset(outbuf, 0, outlen);

	char *in = inbuf;
	char *out = outbuf;
	int ret = iconv(conv, 
					&in,
					&inlen,
					&out,
					&outlen);
	gbkstr.assign(outbuf, strlen(outbuf));
	free(outbuf);
	iconv_close(conv);
	return ret;
#endif
}

#endif
